<template>
  <div class="stats-detail-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800">统计详情</h1>
        </div>
        <div class="flex space-x-3">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            @change="handleDateChange"
          />
          <el-button type="primary" @click="refreshData">
            <el-icon class="mr-1"><i class="el-icon-refresh"></i></el-icon>刷新数据
          </el-button>
          <el-button @click="exportReport">
            <el-icon class="mr-1"><i class="el-icon-download"></i></el-icon>导出报告
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 详情选择器 -->
    <el-card shadow="never" class="mb-6">
      <div class="flex flex-wrap items-center gap-4">
        <div class="flex-1 min-w-[200px]">
          <el-select 
            v-model="detailType" 
            placeholder="选择分析类型" 
            style="width: 100%"
            @change="handleDetailTypeChange"
          >
            <el-option label="新闻详情分析" value="news"></el-option>
            <el-option label="分类详情分析" value="category"></el-option>
            <el-option label="信源详情分析" value="source"></el-option>
            <el-option label="区域详情分析" value="region"></el-option>
            <el-option label="用户行为分析" value="user"></el-option>
          </el-select>
        </div>
        
        <div class="flex-1 min-w-[200px]" v-if="detailType === 'news'">
          <el-select 
            v-model="selectedNews" 
            filterable 
            remote 
            placeholder="搜索新闻标题" 
            :remote-method="searchNews"
            :loading="newsLoading"
            style="width: 100%"
            @change="loadNewsDetail"
          >
            <el-option 
              v-for="item in newsOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        
        <div class="flex-1 min-w-[200px]" v-if="detailType === 'category'">
          <el-select 
            v-model="selectedCategory" 
            placeholder="选择分类" 
            style="width: 100%"
            @change="loadCategoryDetail"
          >
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        
        <div class="flex-1 min-w-[200px]" v-if="detailType === 'source'">
          <el-select 
            v-model="selectedSource" 
            filterable 
            placeholder="选择信源" 
            style="width: 100%"
            @change="loadSourceDetail"
          >
            <el-option 
              v-for="item in sourceOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        
        <div class="flex-1 min-w-[200px]" v-if="detailType === 'region'">
          <el-select 
            v-model="selectedRegion" 
            placeholder="选择区域" 
            style="width: 100%"
            @change="loadRegionDetail"
          >
            <el-option 
              v-for="item in regionOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        
        <div class="flex-1 min-w-[200px]" v-if="detailType === 'user'">
          <el-select 
            v-model="selectedUserBehavior" 
            placeholder="选择用户行为" 
            style="width: 100%"
            @change="loadUserBehaviorDetail"
          >
            <el-option label="阅读行为" value="read"></el-option>
            <el-option label="搜索行为" value="search"></el-option>
            <el-option label="分享行为" value="share"></el-option>
            <el-option label="点击行为" value="click"></el-option>
          </el-select>
        </div>
      </div>
    </el-card>
    
    <!-- 数据概览卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
      <el-card shadow="never" class="stat-card" v-for="(stat, index) in statsCards" :key="index">
        <div class="flex items-center">
          <div :class="stat.iconClass">
            <i :class="stat.icon"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">{{ stat.title }}</div>
            <div class="text-2xl font-bold mt-1">{{ stat.value }}</div>
            <div class="text-xs mt-1" v-if="stat.change !== undefined">
              <span :class="stat.change >= 0 ? 'text-green-500' : 'text-red-500'">
                <i :class="stat.change >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(stat.change) }}%
              </span>
              <span class="text-gray-400 ml-1">较上期</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 趋势图 -->
    <el-card shadow="never" class="mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="text-lg font-medium">{{ trendChartTitle }}</div>
          <div>
            <el-radio-group v-model="trendTimeUnit" size="small" @change="handleTrendUnitChange">
              <el-radio-button label="day">日</el-radio-button>
              <el-radio-button label="week">周</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>
      <div class="h-80" ref="trendChart"></div>
    </el-card>
    
    <!-- 详情分析图表 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- 左侧图表 -->
      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="text-lg font-medium">{{ leftChartTitle }}</div>
            <el-select v-model="leftChartType" size="small" @change="handleLeftChartTypeChange">
              <el-option 
                v-for="option in leftChartOptions" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value"
              ></el-option>
            </el-select>
          </div>
        </template>
        <div class="h-80" ref="leftChart"></div>
      </el-card>
      
      <!-- 右侧图表 -->
      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="text-lg font-medium">{{ rightChartTitle }}</div>
            <el-select v-model="rightChartType" size="small" @change="handleRightChartTypeChange">
              <el-option 
                v-for="option in rightChartOptions" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value"
              ></el-option>
            </el-select>
          </div>
        </template>
        <div class="h-80" ref="rightChart"></div>
      </el-card>
    </div>
    
    <!-- 详情数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="text-lg font-medium">{{ tableTitle }}</div>
          <div class="flex space-x-2">
            <el-input
              v-model="tableSearch"
              placeholder="搜索"
              prefix-icon="el-icon-search"
              clearable
              @input="handleTableSearch"
              style="width: 200px"
            ></el-input>
            <el-button size="small" @click="handleTableRefresh">
              <el-icon><i class="el-icon-refresh"></i></el-icon>
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        style="width: 100%"
        border
        :max-height="500"
      >
        <el-table-column 
          v-for="column in tableColumns" 
          :key="column.prop" 
          :prop="column.prop" 
          :label="column.label" 
          :width="column.width"
          :sortable="column.sortable"
          :fixed="column.fixed"
        >
          <template #default="scope" v-if="column.formatter">
            <span v-html="column.formatter(scope.row[column.prop], scope.row)"></span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

// 注册 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  PieChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
])

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

// 图表实例
let trendChartInstance = null
let leftChartInstance = null
let rightChartInstance = null

// 图表DOM引用
const trendChart = ref(null)
const leftChart = ref(null)
const rightChart = ref(null)

// 日期范围选择
const dateRange = ref([new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), new Date()])
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 趋势图时间单位
const trendTimeUnit = ref('day')

// 详情类型选择
const detailType = ref('news')
const newsLoading = ref(false)
const selectedNews = ref('')
const selectedCategory = ref('')
const selectedSource = ref('')
const selectedRegion = ref('')
const selectedUserBehavior = ref('read')

// 选项数据
const newsOptions = ref([])
const categoryOptions = ref([
  { value: 1, label: '国内' },
  { value: 2, label: '国际' },
  { value: 3, label: '财经' },
  { value: 4, label: '科技' },
  { value: 5, label: '体育' },
  { value: 6, label: '娱乐' },
  { value: 7, label: '教育' },
  { value: 8, label: '健康' }
])

const sourceOptions = ref([
  { value: 1, label: '新华网' },
  { value: 2, label: '人民网' },
  { value: 3, label: '央视网' },
  { value: 4, label: '中国日报' },
  { value: 5, label: '环球时报' },
  { value: 6, label: '财经网' },
  { value: 7, label: '科技日报' },
  { value: 8, label: '体育周报' }
])

const regionOptions = ref([
  { value: 1, label: '北京' },
  { value: 2, label: '上海' },
  { value: 3, label: '广州' },
  { value: 4, label: '深圳' },
  { value: 5, label: '杭州' },
  { value: 6, label: '南京' },
  { value: 7, label: '武汉' },
  { value: 8, label: '成都' }
])

// 图表类型选择
const leftChartType = ref('')
const rightChartType = ref('')
const leftChartOptions = ref([])
const rightChartOptions = ref([])

// 表格相关
const tableTitle = ref('详情数据')
const tableSearch = ref('')
const tableLoading = ref(false)
const tableData = ref([])
const tableColumns = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 统计卡片数据
const statsCards = ref([])

// 图表标题
const trendChartTitle = ref('趋势分析')
const leftChartTitle = ref('分布分析')
const rightChartTitle = ref('对比分析')

// 格式化数字
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 搜索新闻
const searchNews = (query) => {
  if (query) {
    newsLoading.value = true
      // 模拟搜索结果
  newsOptions.value = [
    { value: 101, label: '国务院关于加强经济发展的重要指示' },
    { value: 102, label: '美联储宣布加息25个基点，为今年第三次加息' },
    { value: 103, label: '世界杯预选赛：中国队2:0战胜泰国队' },
    { value: 104, label: '新一代人工智能技术发展报告发布' },
    { value: 105, label: '电影《流浪地球3》定档明年春节' }
  ].filter(item => item.label.toLowerCase().includes(query.toLowerCase()))
  newsLoading.value = false
  } else {
    newsOptions.value = []
  }
}

// 详情类型变化处理
const handleDetailTypeChange = () => {
  // 重置选择
  selectedNews.value = ''
  selectedCategory.value = ''
  selectedSource.value = ''
  selectedRegion.value = ''
  
  // 根据类型设置默认图表选项
  setupChartOptions()
  
  // 清空数据
  statsCards.value = []
  tableData.value = []
  tableColumns.value = []
  
  // 设置表格标题
  switch (detailType.value) {
    case 'news':
      tableTitle.value = '新闻访问详情'
      break
    case 'category':
      tableTitle.value = '分类内容详情'
      break
    case 'source':
      tableTitle.value = '信源内容详情'
      break
    case 'region':
      tableTitle.value = '区域内容详情'
      break
    case 'user':
      tableTitle.value = '用户行为详情'
      break
  }
}

// 设置图表选项
const setupChartOptions = () => {
  switch (detailType.value) {
    case 'news':
      leftChartOptions.value = [
        { value: 'device', label: '设备分布' },
        { value: 'source', label: '来源分布' },
        { value: 'region', label: '地域分布' }
      ]
      rightChartOptions.value = [
        { value: 'time', label: '时段分布' },
        { value: 'duration', label: '停留时长' },
        { value: 'action', label: '用户行为' }
      ]
      leftChartType.value = 'device'
      rightChartType.value = 'time'
      trendChartTitle.value = '新闻访问趋势'
      leftChartTitle.value = '访问设备分布'
      rightChartTitle.value = '访问时段分布'
      break
    case 'category':
      leftChartOptions.value = [
        { value: 'news', label: '新闻分布' },
        { value: 'source', label: '信源分布' },
        { value: 'region', label: '地域分布' }
      ]
      rightChartOptions.value = [
        { value: 'reads', label: '阅读量对比' },
        { value: 'shares', label: '分享量对比' },
        { value: 'comments', label: '评论量对比' }
      ]
      leftChartType.value = 'news'
      rightChartType.value = 'reads'
      trendChartTitle.value = '分类内容趋势'
      leftChartTitle.value = '新闻分布'
      rightChartTitle.value = '阅读量对比'
      break
    case 'source':
      leftChartOptions.value = [
        { value: 'category', label: '分类分布' },
        { value: 'region', label: '区域分布' },
        { value: 'quality', label: '内容质量' }
      ]
      rightChartOptions.value = [
        { value: 'reads', label: '阅读量对比' },
        { value: 'update', label: '更新频率' },
        { value: 'growth', label: '增长趋势' }
      ]
      leftChartType.value = 'category'
      rightChartType.value = 'reads'
      trendChartTitle.value = '信源内容趋势'
      leftChartTitle.value = '分类分布'
      rightChartTitle.value = '阅读量对比'
      break
    case 'region':
      leftChartOptions.value = [
        { value: 'category', label: '分类分布' },
        { value: 'source', label: '信源分布' },
        { value: 'topic', label: '热门话题' }
      ]
      rightChartOptions.value = [
        { value: 'reads', label: '阅读量对比' },
        { value: 'shares', label: '分享量对比' },
        { value: 'growth', label: '增长趋势' }
      ]
      leftChartType.value = 'category'
      rightChartType.value = 'reads'
      trendChartTitle.value = '区域内容趋势'
      leftChartTitle.value = '分类分布'
      rightChartTitle.value = '阅读量对比'
      break
    case 'user':
      leftChartOptions.value = [
        { value: 'device', label: '设备分布' },
        { value: 'region', label: '地域分布' },
        { value: 'preference', label: '兴趣偏好' }
      ]
      rightChartOptions.value = [
        { value: 'frequency', label: '访问频率' },
        { value: 'duration', label: '停留时长' },
        { value: 'path', label: '访问路径' }
      ]
      leftChartType.value = 'device'
      rightChartType.value = 'frequency'
      trendChartTitle.value = '用户行为趋势'
      leftChartTitle.value = '设备分布'
      rightChartTitle.value = '访问频率'
      break
  }
}

// 加载新闻详情
const loadNewsDetail = () => {
  if (!selectedNews.value) return
  
  // 模拟加载数据
  tableLoading.value = true
  
  // 设置统计卡片
  statsCards.value = [
    {
      title: '总访问量',
      value: formatNumber(12568),
      change: 15.2,
      icon: 'el-icon-view',
      iconClass: 'stat-icon bg-blue-100 text-blue-500'
    },
    {
      title: '独立访客',
      value: formatNumber(8432),
      change: 12.8,
      icon: 'el-icon-user',
      iconClass: 'stat-icon bg-green-100 text-green-500'
    },
    {
      title: '平均停留时间',
      value: '2:45',
      change: 8.5,
      icon: 'el-icon-timer',
      iconClass: 'stat-icon bg-orange-100 text-orange-500'
    },
    {
      title: '分享次数',
      value: formatNumber(3254),
      change: 25.7,
      icon: 'el-icon-share',
      iconClass: 'stat-icon bg-red-100 text-red-500'
    }
  ]
  
  // 设置表格列
  tableColumns.value = [
    { prop: 'date', label: '日期', width: '120', sortable: true },
    { prop: 'pv', label: '访问量', width: '100', sortable: true },
    { prop: 'uv', label: '访客数', width: '100', sortable: true },
    { prop: 'ip', label: 'IP数', width: '100', sortable: true },
    { prop: 'avg_duration', label: '平均停留时间', width: '140', sortable: true },
    { prop: 'bounce_rate', label: '跳出率', width: '100', sortable: true, formatter: (val) => `${val}%` },
    { prop: 'shares', label: '分享次数', width: '100', sortable: true },
    { prop: 'device_type', label: '主要设备', width: '120' },
    { prop: 'source_type', label: '主要来源', width: '120' }
  ]
  
  // 生成最近30天的数据
  const data = []
  for (let i = 29; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    
    data.push({
      date: dateStr,
      pv: Math.floor(Math.random() * 500) + 300,
      uv: Math.floor(Math.random() * 300) + 200,
      ip: Math.floor(Math.random() * 250) + 180,
      avg_duration: `${Math.floor(Math.random() * 3) + 1}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
      bounce_rate: (Math.random() * 20 + 30).toFixed(1),
      shares: Math.floor(Math.random() * 150) + 50,
      device_type: Math.random() > 0.7 ? '移动端' : '桌面端',
      source_type: ['直接访问', '搜索引擎', '外部链接', '社交媒体'][Math.floor(Math.random() * 4)]
    })
  }
  
  tableData.value = data
  total.value = data.length
  tableLoading.value = false
  
  // 渲染图表
  nextTick(() => {
    renderTrendChart()
    renderLeftChart()
    renderRightChart()
  })
}

// 加载分类详情
const loadCategoryDetail = () => {
  if (!selectedCategory.value) return
  
  // 模拟加载数据
  tableLoading.value = true
  
  // 设置统计卡片
  statsCards.value = [
    {
      title: '新闻总数',
      value: formatNumber(1245),
      change: 5.2,
      icon: 'el-icon-document',
      iconClass: 'stat-icon bg-blue-100 text-blue-500 '
    },
    {
      title: '总阅读量',
      value: formatNumber(85432),
      change: 12.8,
      icon: 'el-icon-reading',
      iconClass: 'stat-icon bg-green-100 text-green-500'
    },
    {
      title: '平均阅读量',
      value: formatNumber(68),
      change: 7.5,
      icon: 'el-icon-data-line',
      iconClass: 'stat-icon bg-orange-100 text-orange-500'
    },
    {
      title: '信源数量',
      value: formatNumber(12),
      change: 0,
      icon: 'el-icon-collection',
      iconClass: 'stat-icon bg-red-100 text-red-500'
    }
  ]
  
  // 设置表格列
  tableColumns.value = [
    { prop: 'id', label: 'ID', width: '80', sortable: true },
    { prop: 'title', label: '标题', minWidth: '300' },
    { prop: 'source', label: '来源', width: '120' },
    { prop: 'publish_time', label: '发布时间', width: '180', sortable: true },
    { prop: 'reads', label: '阅读量', width: '100', sortable: true },
    { prop: 'shares', label: '分享量', width: '100', sortable: true },
    { prop: 'comments', label: '评论量', width: '100', sortable: true }
  ]
  
  // 生成分类下的新闻数据
  const categoryName = categoryOptions.value.find(item => item.value === selectedCategory.value)?.label || '未知分类'
  const data = []
  
  for (let i = 1; i <= 50; i++) {
    const date = new Date()
    date.setDate(date.getDate() - Math.floor(Math.random() * 30))
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    
    data.push({
      id: i,
      title: `${categoryName}新闻${i}: ${['重要政策解读', '最新动态报道', '深度分析', '热点评论', '专题报道'][Math.floor(Math.random() * 5)]}`,
      source: sourceOptions.value[Math.floor(Math.random() * sourceOptions.value.length)].label,
      publish_time: dateStr,
      reads: Math.floor(Math.random() * 10000) + 1000,
      shares: Math.floor(Math.random() * 500) + 100,
      comments: Math.floor(Math.random() * 300) + 50
    })
  }
  
  // 按阅读量排序
  data.sort((a, b) => b.reads - a.reads)
  
  tableData.value = data
  total.value = data.length
  tableLoading.value = false
  
  // 渲染图表
  nextTick(() => {
    renderTrendChart()
    renderLeftChart()
    renderRightChart()
  })
}

// 加载信源详情
const loadSourceDetail = () => {
  if (!selectedSource.value) return
  
  // 模拟加载数据
  tableLoading.value = true
  
  // 设置统计卡片
  statsCards.value = [
    {
      title: '新闻总数',
      value: formatNumber(856),
      change: 8.2,
      icon: 'el-icon-document',
      iconClass: 'stat-icon bg-blue-100 text-blue-500'
    },
    {
      title: '总阅读量',
      value: formatNumber(65432),
      change: 15.8,
      icon: 'el-icon-reading',
      iconClass: 'stat-icon bg-green-100 text-green-500'
    },
    {
      title: '平均阅读量',
      value: formatNumber(76),
      change: 7.0,
      icon: 'el-icon-data-line',
      iconClass: 'stat-icon bg-orange-100 text-orange-500'
    },
    {
      title: '更新频率',
      value: '每日12篇',
      change: 16.7,
      icon: 'el-icon-refresh',
      iconClass: 'stat-icon bg-red-100 text-red-500'
    }
  ]
  
  // 设置表格列
  tableColumns.value = [
    { prop: 'id', label: 'ID', width: '80', sortable: true },
    { prop: 'title', label: '标题', minWidth: '300' },
    { prop: 'category', label: '分类', width: '120' },
    { prop: 'publish_time', label: '发布时间', width: '180', sortable: true },
    { prop: 'reads', label: '阅读量', width: '100', sortable: true },
    { prop: 'shares', label: '分享量', width: '100', sortable: true },
    { prop: 'comments', label: '评论量', width: '100', sortable: true }
  ]
  
  // 生成信源下的新闻数据
  const sourceName = sourceOptions.value.find(item => item.value === selectedSource.value)?.label || '未知信源'
  const data = []
  
  for (let i = 1; i <= 50; i++) {
    const date = new Date()
    date.setDate(date.getDate() - Math.floor(Math.random() * 30))
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    
    data.push({
      id: i,
      title: `${sourceName}报道${i}: ${['重要政策解读', '最新动态报道', '深度分析', '热点评论', '专题报道'][Math.floor(Math.random() * 5)]}`,
      category: categoryOptions.value[Math.floor(Math.random() * categoryOptions.value.length)].label,
      publish_time: dateStr,
      reads: Math.floor(Math.random() * 10000) + 1000,
      shares: Math.floor(Math.random() * 500) + 100,
      comments: Math.floor(Math.random() * 300) + 50
    })
  }
  
  // 按发布时间排序
  data.sort((a, b) => new Date(b.publish_time) - new Date(a.publish_time))
  
  tableData.value = data
  total.value = data.length
  tableLoading.value = false
  
  // 渲染图表
  nextTick(() => {
    renderTrendChart()
    renderLeftChart()
    renderRightChart()
  })
}

// 加载区域详情
const loadRegionDetail = () => {
  if (!selectedRegion.value) return
  
  // 模拟加载数据
  tableLoading.value = true
  
  // 设置统计卡片
  statsCards.value = [
    {
      title: '新闻总数',
      value: formatNumber(1024),
      change: 6.2,
      icon: 'el-icon-document',
      iconClass: 'stat-icon bg-blue-100 text-blue-500'
    },
    {
      title: '总阅读量',
      value: formatNumber(78432),
      change: 10.8,
      icon: 'el-icon-reading',
      iconClass: 'stat-icon bg-green-100 text-green-500'
    },
    {
      title: '信源数量',
      value: formatNumber(15),
      change: 7.1,
      icon: 'el-icon-collection',
      iconClass: 'stat-icon bg-orange-100 text-orange-500'
    },
    {
      title: '热门话题',
      value: formatNumber(8),
      change: 33.3,
      icon: 'el-icon-hot-water',
      iconClass: 'stat-icon bg-red-100 text-red-500'
    }
  ]
  
  // 设置表格列
  tableColumns.value = [
    { prop: 'id', label: 'ID', width: '80', sortable: true },
    { prop: 'title', label: '标题', minWidth: '300' },
    { prop: 'category', label: '分类', width: '120' },
    { prop: 'source', label: '来源', width: '120' },
    { prop: 'publish_time', label: '发布时间', width: '180', sortable: true },
    { prop: 'reads', label: '阅读量', width: '100', sortable: true },
    { prop: 'shares', label: '分享量', width: '100', sortable: true }
  ]
  
  // 生成区域下的新闻数据
  const regionName = regionOptions.value.find(item => item.value === selectedRegion.value)?.label || '未知区域'
  const data = []
  
  for (let i = 1; i <= 50; i++) {
    const date = new Date()
    date.setDate(date.getDate() - Math.floor(Math.random() * 30))
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    
    data.push({
      id: i,
      title: `${regionName}新闻${i}: ${['城市发展', '经济动态', '文化活动', '民生工程', '政策解读'][Math.floor(Math.random() * 5)]}`,
      category: categoryOptions.value[Math.floor(Math.random() * categoryOptions.value.length)].label,
      source: sourceOptions.value[Math.floor(Math.random() * sourceOptions.value.length)].label,
      publish_time: dateStr,
      reads: Math.floor(Math.random() * 10000) + 1000,
      shares: Math.floor(Math.random() * 500) + 100
    })
  }
  
  // 按阅读量排序
  data.sort((a, b) => b.reads - a.reads)
  
  tableData.value = data
  total.value = data.length
  tableLoading.value = false
  
  // 渲染图表
  nextTick(() => {
    renderTrendChart()
    renderLeftChart()
    renderRightChart()
  })
}

// 加载用户行为详情
const loadUserBehaviorDetail = () => {
  if (!selectedUserBehavior.value) return
  
  // 模拟加载数据
  tableLoading.value = true
  
  // 设置统计卡片
  statsCards.value = [
    {
      title: '用户总数',
      value: formatNumber(45689),
      change: 12.2,
      icon: 'el-icon-user',
      iconClass: 'stat-icon bg-blue-100 text-blue-500'
    },
    {
      title: '活跃用户',
      value: formatNumber(12543),
      change: 8.8,
      icon: 'el-icon-user-solid',
      iconClass: 'stat-icon bg-green-100 text-green-500'
    },
    {
      title: '平均访问频率',
      value: '每周3.5次',
      change: 5.1,
      icon: 'el-icon-data-line',
      iconClass: 'stat-icon bg-orange-100 text-orange-500'
    },
    {
      title: '平均停留时间',
      value: '8:45',
      change: 15.3,
      icon: 'el-icon-timer',
      iconClass: 'stat-icon bg-red-100 text-red-500'
    }
  ]
  
  // 设置表格列
  if (selectedUserBehavior.value === 'read') {
    tableColumns.value = [
      { prop: 'date', label: '日期', width: '120', sortable: true },
      { prop: 'user_type', label: '用户类型', width: '120' },
      { prop: 'news_count', label: '阅读文章数', width: '120', sortable: true },
      { prop: 'avg_duration', label: '平均阅读时长', width: '140', sortable: true },
      { prop: 'category_preference', label: '分类偏好', width: '120' },
      { prop: 'source_preference', label: '信源偏好', width: '120' },
      { prop: 'device_type', label: '设备类型', width: '120' },
      { prop: 'region', label: '区域', width: '120' }
    ]
  } else if (selectedUserBehavior.value === 'search') {
    tableColumns.value = [
      { prop: 'date', label: '日期', width: '120', sortable: true },
      { prop: 'keyword', label: '搜索关键词', minWidth: '200' },
      { prop: 'search_count', label: '搜索次数', width: '120', sortable: true },
      { prop: 'result_count', label: '结果数', width: '120' },
      { prop: 'click_rate', label: '点击率', width: '120', sortable: true, formatter: (val) => `${val}%` },
      { prop: 'user_type', label: '用户类型', width: '120' },
      { prop: 'device_type', label: '设备类型', width: '120' }
    ]
  } else if (selectedUserBehavior.value === 'share') {
    tableColumns.value = [
      { prop: 'date', label: '日期', width: '120', sortable: true },
      { prop: 'news_title', label: '分享内容', minWidth: '200' },
      { prop: 'share_count', label: '分享次数', width: '120', sortable: true },
      { prop: 'platform', label: '分享平台', width: '120' },
      { prop: 'user_type', label: '用户类型', width: '120' },
      { prop: 'category', label: '内容分类', width: '120' },
      { prop: 'device_type', label: '设备类型', width: '120' }
    ]
  } else if (selectedUserBehavior.value === 'click') {
    tableColumns.value = [
      { prop: 'date', label: '日期', width: '120', sortable: true },
      { prop: 'element', label: '点击元素', minWidth: '200' },
      { prop: 'click_count', label: '点击次数', width: '120', sortable: true },
      { prop: 'page', label: '所在页面', width: '150' },
      { prop: 'position', label: '位置', width: '120' },
      { prop: 'user_type', label: '用户类型', width: '120' },
      { prop: 'device_type', label: '设备类型', width: '120' }
    ]
  }
  
  const data = []
  
  if (selectedUserBehavior.value === 'read') {
    // 阅读行为数据
    for (let i = 1; i <= 50; i++) {
      const date = new Date()
      date.setDate(date.getDate() - Math.floor(Math.random() * 30))
      const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      
      data.push({
        date: dateStr,
        user_type: ['新用户', '回访用户', '活跃用户', '忠实用户'][Math.floor(Math.random() * 4)],
        news_count: Math.floor(Math.random() * 20) + 1,
        avg_duration: `${Math.floor(Math.random() * 10) + 1}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
        category_preference: categoryOptions.value[Math.floor(Math.random() * categoryOptions.value.length)].label,
        source_preference: sourceOptions.value[Math.floor(Math.random() * sourceOptions.value.length)].label,
        device_type: Math.random() > 0.7 ? '移动端' : '桌面端',
        region: regionOptions.value[Math.floor(Math.random() * regionOptions.value.length)].label
      })
    }
  } else if (selectedUserBehavior.value === 'search') {
    // 搜索行为数据
    const keywords = ['疫情', '经济', '政策', '科技', '教育', '医疗', '房产', '体育', '娱乐', '国际']
    
    for (let i = 1; i <= 50; i++) {
      const date = new Date()
      date.setDate(date.getDate() - Math.floor(Math.random() * 30))
      const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      
      data.push({
        date: dateStr,
        keyword: keywords[Math.floor(Math.random() * keywords.length)],
        search_count: Math.floor(Math.random() * 100) + 1,
        result_count: Math.floor(Math.random() * 200) + 10,
        click_rate: (Math.random() * 50 + 20).toFixed(1),
        user_type: ['新用户', '回访用户', '活跃用户', '忠实用户'][Math.floor(Math.random() * 4)],
        device_type: Math.random() > 0.7 ? '移动端' : '桌面端'
      })
    }
  } else if (selectedUserBehavior.value === 'share') {
    // 分享行为数据
    const platforms = ['微信', '微博', '朋友圈', 'QQ', '钉钉', '邮件', '复制链接']
    
    for (let i = 1; i <= 50; i++) {
      const date = new Date()
      date.setDate(date.getDate() - Math.floor(Math.random() * 30))
      const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      
      data.push({
        date: dateStr,
        news_title: `热门新闻${i}: ${['重要政策解读', '最新动态报道', '深度分析', '热点评论', '专题报道'][Math.floor(Math.random() * 5)]}`,
        share_count: Math.floor(Math.random() * 50) + 1,
        platform: platforms[Math.floor(Math.random() * platforms.length)],
        user_type: ['新用户', '回访用户', '活跃用户', '忠实用户'][Math.floor(Math.random() * 4)],
        category: categoryOptions.value[Math.floor(Math.random() * categoryOptions.value.length)].label,
        device_type: Math.random() > 0.7 ? '移动端' : '桌面端'
      })
    }
  } else if (selectedUserBehavior.value === 'click') {
    // 点击行为数据
    const elements = ['导航菜单', '新闻卡片', '分类标签', '搜索框', '分享按钮', '评论按钮', '用户头像', '相关推荐', '广告位', '返回顶部']
    const pages = ['首页', '分类页', '详情页', '搜索结果页', '个人中心']
    
    for (let i = 1; i <= 50; i++) {
      const date = new Date()
      date.setDate(date.getDate() - Math.floor(Math.random() * 30))
      const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      
      data.push({
        date: dateStr,
        element: elements[Math.floor(Math.random() * elements.length)],
        click_count: Math.floor(Math.random() * 200) + 50,
        page: pages[Math.floor(Math.random() * pages.length)],
        position: ['顶部', '中部', '底部', '左侧', '右侧'][Math.floor(Math.random() * 5)],
        user_type: ['新用户', '回访用户', '活跃用户', '忠实用户'][Math.floor(Math.random() * 4)],
        device_type: Math.random() > 0.7 ? '移动端' : '桌面端'
      })
    }
  }
  
  // 按日期排序
  data.sort((a, b) => new Date(b.date) - new Date(a.date))
  
  tableData.value = data
  total.value = data.length
  tableLoading.value = false
  
  // 渲染图表
  nextTick(() => {
    renderTrendChart()
    renderLeftChart()
    renderRightChart()
  })
}

// 日期变化处理
const handleDateChange = () => {
  // 重新加载数据
  refreshData()
}

// 趋势图时间单位变化处理
const handleTrendUnitChange = () => {
  // 重新渲染趋势图
  renderTrendChart()
}

// 左侧图表类型变化处理
const handleLeftChartTypeChange = () => {
  // 更新图表标题
  updateChartTitles()
  // 重新渲染左侧图表
  renderLeftChart()
}

// 右侧图表类型变化处理
const handleRightChartTypeChange = () => {
  // 更新图表标题
  updateChartTitles()
  // 重新渲染右侧图表
  renderRightChart()
}

// 更新图表标题
const updateChartTitles = () => {
  // 左侧图表标题
  const leftOption = leftChartOptions.value.find(option => option.value === leftChartType.value)
  if (leftOption) {
    leftChartTitle.value = leftOption.label
  }
  
  // 右侧图表标题
  const rightOption = rightChartOptions.value.find(option => option.value === rightChartType.value)
  if (rightOption) {
    rightChartTitle.value = rightOption.label
  }
}

// 表格搜索处理
const handleTableSearch = () => {
  // 这里应该是实际的表格搜索逻辑
  tableLoading.value = true
  tableLoading.value = false
}

// 表格刷新处理
const handleTableRefresh = () => {
  // 重新加载表格数据
  tableLoading.value = true
  tableLoading.value = false
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}

// 刷新数据
const refreshData = () => {
  // 这里应该是实际的数据加载逻辑
  // 模拟数据加载
  ElMessage({
    type: 'success',
    message: '数据已刷新',
  })
  
  // 根据当前选择的详情类型重新加载数据
  switch (detailType.value) {
    case 'news':
      if (selectedNews.value) loadNewsDetail()
      break
    case 'category':
      if (selectedCategory.value) loadCategoryDetail()
      break
    case 'source':
      if (selectedSource.value) loadSourceDetail()
      break
    case 'region':
      if (selectedRegion.value) loadRegionDetail()
      break
    case 'user':
      if (selectedUserBehavior.value) loadUserBehaviorDetail()
      break
  }
}

// 导出报告
const exportReport = () => {
  ElMessage({
    type: 'success',
    message: '报告导出成功',
  })
}

// 渲染趋势图
const renderTrendChart = () => {
  if (!trendChart.value) return
  
  // 销毁旧实例
  if (trendChartInstance) {
    trendChartInstance.dispose()
  }
  
  // 创建新实例
  trendChartInstance = echarts.init(trendChart.value, null, {
    renderer: 'canvas'
  })
  
  // 模拟数据
  let xAxisData = []
  let seriesData = []
  let seriesData2 = []
  
  // 根据时间单位生成数据
  if (trendTimeUnit.value === 'day') {
    // 生成最近30天的数据
    for (let i = 29; i >= 0; i--) {
      const date = new Date()
      date.setDate(date.getDate() - i)
      xAxisData.push(`${date.getMonth() + 1}/${date.getDate()}`)
      seriesData.push(Math.floor(Math.random() * 1000) + 500)
      seriesData2.push(Math.floor(Math.random() * 800) + 300)
    }
  } else if (trendTimeUnit.value === 'week') {
    // 生成最近12周的数据
    for (let i = 11; i >= 0; i--) {
      xAxisData.push(`第${12-i}周`)
      seriesData.push(Math.floor(Math.random() * 5000) + 3000)
      seriesData2.push(Math.floor(Math.random() * 4000) + 2000)
    }
  } else if (trendTimeUnit.value === 'month') {
    // 生成最近12个月的数据
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    const currentMonth = new Date().getMonth()
    
    for (let i = 11; i >= 0; i--) {
      const monthIndex = (currentMonth - i + 12) % 12
      xAxisData.push(months[monthIndex])
      seriesData.push(Math.floor(Math.random() * 20000) + 10000)
      seriesData2.push(Math.floor(Math.random() * 15000) + 8000)
    }
  }
  
  // 设置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['访问量', '用户数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '访问量',
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#5470c6'
          }
        },
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '用户数',
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#91cc75'
          }
        },
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '访问量',
        type: 'line',
        smooth: true,
        data: seriesData
      },
      {
        name: '用户数',
        type: 'bar',
        yAxisIndex: 1,
        data: seriesData2
      }
    ]
  }
  
  // 设置图表
  trendChartInstance.setOption(option)
  
  // 响应式调整大小
  window.addEventListener('resize', () => {
    trendChartInstance.resize()
  })
}

// 渲染左侧图表
const renderLeftChart = () => {
  if (!leftChart.value) return
  
  // 销毁旧实例
  if (leftChartInstance) {
    leftChartInstance.dispose()
  }
  
  // 创建新实例
  leftChartInstance = echarts.init(leftChart.value, null, {
    renderer: 'canvas'
  })
  
  // 根据图表类型设置不同的选项
  let option = {}
  
  if (rightChartType.value === 'time' || 
      rightChartType.value === 'frequency') {
    // 时段分布/访问频率 - 柱状图
    const xAxisData = []
    const seriesData = []
    
    if (rightChartType.value === 'time') {
      // 时段分布 - 24小时
      for (let i = 0; i < 24; i++) {
        xAxisData.push(`${i}:00`)
        // 模拟不同时段的访问量分布
        if (i >= 8 && i <= 12) {
          // 上午高峰
          seriesData.push(Math.floor(Math.random() * 300) + 700)
        } else if (i >= 19 && i <= 23) {
          // 晚上高峰
          seriesData.push(Math.floor(Math.random() * 400) + 800)
        } else if (i >= 14 && i <= 17) {
          // 下午中等
          seriesData.push(Math.floor(Math.random() * 200) + 500)
        } else {
          // 其他时段低谷
          seriesData.push(Math.floor(Math.random() * 200) + 100)
        }
      }
    } else if (rightChartType.value === 'frequency') {
      // 访问频率
      xAxisData.push('每天', '每周2-3次', '每周1次', '每月2-3次', '每月1次', '更少')
      seriesData.push(3500, 2500, 1800, 1200, 800, 500)
    }
    
    // 柱状图配置
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: rightChartTitle.value,
          type: 'bar',
          barWidth: '60%',
          data: seriesData
        }
      ]
    }
  } else if (rightChartType.value === 'duration' || 
             rightChartType.value === 'path') {
    // 停留时长/访问路径 - 饼图
    const pieData = []
    let names = []
    
    if (rightChartType.value === 'duration') {
      // 停留时长分布
      names = ['<1分钟', '1-3分钟', '3-5分钟', '5-10分钟', '10-30分钟', '>30分钟']
      pieData.push(
        { name: names[0], value: 1500 },
        { name: names[1], value: 2500 },
        { name: names[2], value: 1800 },
        { name: names[3], value: 1200 },
        { name: names[4], value: 500 },
        { name: names[5], value: 200 }
      )
    } else if (rightChartType.value === 'path') {
      // 访问路径分布
      names = ['首页直达', '搜索跳转', '分类页进入', '推荐链接', '相关新闻', '其他']
      pieData.push(
        { name: names[0], value: 3500 },
        { name: names[1], value: 2800 },
        { name: names[2], value: 1500 },
        { name: names[3], value: 1200 },
        { name: names[4], value: 800 },
        { name: names[5], value: 500 }
      )
    }
    
    // 饼图配置
    option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: names
      },
      series: [
        {
          name: rightChartTitle.value,
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: pieData
        }
      ]
    }
  } else if (rightChartType.value === 'reads' || 
             rightChartType.value === 'shares' || 
             rightChartType.value === 'comments' || 
             rightChartType.value === 'update' || 
             rightChartType.value === 'growth' || 
             rightChartType.value === 'action') {
    // 对比分析 - 柱状图
    const xAxisData = []
    const seriesData = []
    
    if (rightChartType.value === 'reads' || 
        rightChartType.value === 'shares' || 
        rightChartType.value === 'comments') {
      // 阅读量/分享量/评论量对比
      if (detailType.value === 'category') {
        // 分类对比
        categoryOptions.value.forEach(item => {
          xAxisData.push(item.label)
          seriesData.push(Math.floor(Math.random() * 10000) + 1000)
        })
      } else if (detailType.value === 'source') {
        // 信源对比
        sourceOptions.value.forEach(item => {
          xAxisData.push(item.label)
          seriesData.push(Math.floor(Math.random() * 10000) + 1000)
        })
      } else if (detailType.value === 'region') {
        // 区域对比
        regionOptions.value.forEach(item => {
          xAxisData.push(item.label)
          seriesData.push(Math.floor(Math.random() * 10000) + 1000)
        })
      }
    } else if (rightChartType.value === 'update') {
      // 更新频率
      xAxisData.push('每日多次', '每日一次', '每周2-3次', '每周一次', '更少')
      seriesData.push(3, 5, 8, 4, 2)
    } else if (rightChartType.value === 'growth') {
      // 增长趋势
      for (let i = 6; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        xAxisData.push(`${date.getMonth() + 1}/${date.getDate()}`)
        // 模拟增长率，-10% 到 30% 之间
        seriesData.push((Math.random() * 40 - 10).toFixed(1))
      }
    } else if (rightChartType.value === 'action') {
      // 用户行为
      xAxisData.push('阅读', '点赞', '评论', '分享', '收藏', '关注')
      seriesData.push(1000, 500, 300, 400, 200, 100)
    }
    
    // 柱状图配置
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            rotate: rightChartType.value === 'reads' || 
                    rightChartType.value === 'shares' || 
                    rightChartType.value === 'comments' ? 45 : 0,
            interval: 0
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          axisLabel: {
            formatter: rightChartType.value === 'growth' ? '{value}%' : '{value}'
          }
        }
      ],
      series: [
        {
          name: rightChartTitle.value,
          type: 'bar',
          barWidth: '60%',
          data: seriesData,
          itemStyle: {
            color: function(params) {
              // 增长趋势图中，负值显示红色，正值显示绿色
              if (rightChartType.value === 'growth') {
                return params.data >= 0 ? '#67C23A' : '#F56C6C'
              }
              return ''
            }
          }
        }
      ]
    }
  }
  
  // 设置图表
  rightChartInstance.setOption(option)
  
  // 响应式调整大小
  window.addEventListener('resize', () => {
    rightChartInstance.resize()
  })
}

// 页面初始化
onMounted(() => {
  // 设置默认图表选项
  setupChartOptions()
  
  // 初始化图表
  nextTick(() => {
    renderTrendChart()
    renderLeftChart()
    renderRightChart()
  })
})

// 监听详情类型变化
watch(detailType, () => {
  handleDetailTypeChange()
})

// 监听图表类型变化
watch([leftChartType, rightChartType], () => {
  updateChartTitles()
})
  </script>

<style scoped>
.stats-detail-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.stat-card {
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

/* 暗色模式适配 */










</style>
  } else if (leftChartType.value === 'news' || 
             leftChartType.value === 'quality' || 
             leftChartType.value === 'topic') {
    // 柱状图数据
    const xAxisData = []
    const seriesData = []
    
    // 根据图表类型设置不同的数据
    if (leftChartType.value === 'news') {
      // 新闻分布 - 显示最近10天的新闻数量
      for (let i = 9; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        xAxisData.push(`${date.getMonth() + 1}/${date.getDate()}`)
        seriesData.push(Math.floor(Math.random() * 50) + 10)
      }
    } else if (leftChartType.value === 'quality') {
      // 内容质量分布
      xAxisData.push('优', '良', '中', '一般', '差')
      seriesData.push(45, 25, 15, 10, 5)
    } else if (leftChartType.value === 'topic') {
      // 热门话题分布
      xAxisData.push('话题1', '话题2', '话题3', '话题4', '话题5', '话题6')
      seriesData.push(120, 90, 70, 60, 50, 40)
    }
    
    // 柱状图配置
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: leftChartTitle.value,
          type: 'bar',
          barWidth: '60%',
          data: seriesData
        }
      ]
    }
  }
  
  // 设置图表
  leftChartInstance.setOption(option)
  
  // 响应式调整大小
  window.addEventListener('resize', () => {
    leftChartInstance.resize()
  })
}

// 渲染右侧图表
const renderRightChart = () => {
  if (!rightChart.value) return
  
  // 销毁旧实例
  if (rightChartInstance) {
    rightChartInstance.dispose()
  }
  
  // 创建新实例
  rightChartInstance = echarts.init(rightChart.value, null, {
    renderer: 'canvas'
  })
  
  // 根据图表类型设置不同的选项
  let option = {}